// NCM转MP3转换器主逻辑
class NCMConverter {
    constructor() {
        this.files = [];
        this.initializeElements();
        this.bindEvents();
    }

    initializeElements() {
        this.dropZone = document.getElementById('dropZone');
        this.fileInput = document.getElementById('fileInput');
        this.fileList = document.getElementById('fileList');
        this.fileItems = document.getElementById('fileItems');
        this.actions = document.getElementById('actions');
        this.saveBtn = document.getElementById('saveBtn');
        this.clearBtn = document.getElementById('clearBtn');
    }

    bindEvents() {
        // 拖拽事件
        this.dropZone.addEventListener('dragover', this.handleDragOver.bind(this));
        this.dropZone.addEventListener('dragleave', this.handleDragLeave.bind(this));
        this.dropZone.addEventListener('drop', this.handleDrop.bind(this));
        this.dropZone.addEventListener('click', () => this.fileInput.click());

        // 文件选择事件
        this.fileInput.addEventListener('change', this.handleFileSelect.bind(this));

        // 按钮事件
        this.saveBtn.addEventListener('click', this.handleSave.bind(this));
        this.clearBtn.addEventListener('click', this.handleClear.bind(this));
    }

    handleDragOver(e) {
        e.preventDefault();
        this.dropZone.classList.add('dragover');
    }

    handleDragLeave(e) {
        e.preventDefault();
        this.dropZone.classList.remove('dragover');
    }

    handleDrop(e) {
        e.preventDefault();
        this.dropZone.classList.remove('dragover');
        
        const files = Array.from(e.dataTransfer.files).filter(file => 
            file.name.toLowerCase().endsWith('.ncm')
        );
        
        if (files.length === 0) {
            alert('请拖拽 .ncm 格式的文件');
            return;
        }
        
        this.addFiles(files);
    }

    handleFileSelect(e) {
        const files = Array.from(e.target.files);
        this.addFiles(files);
        e.target.value = '';
    }

    addFiles(newFiles) {
        newFiles.forEach(file => {
            if (!file.name.toLowerCase().endsWith('.ncm')) {
                alert(`${file.name} 不是 .ncm 格式文件`);
                return;
            }
            
            const existingFile = this.files.find(f => f.name === file.name && f.size === file.size);
            if (!existingFile) {
                this.files.push({
                    file,
                    name: file.name,
                    size: file.size,
                    status: 'pending',
                    progress: 0,
                    mp3Data: null
                });
            }
        });
        
        this.renderFileList();
        this.startConversion();
    }

    renderFileList() {
        if (this.files.length === 0) {
            this.fileList.style.display = 'none';
            this.actions.style.display = 'none';
            return;
        }

        this.fileList.style.display = 'block';
        this.actions.style.display = 'flex';

        this.fileItems.innerHTML = '';
        
        this.files.forEach((item, index) => {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            
            fileItem.innerHTML = `
                <div class="file-info">
                    <div class="file-name">${item.name}</div>
                    <div class="file-size">${this.formatFileSize(item.size)}</div>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${item.progress}%"></div>
                    </div>
                </div>
                <div class="status ${item.status}">
                    ${this.getStatusText(item.status)}
                </div>
            `;
            
            this.fileItems.appendChild(fileItem);
        });
    }

    async startConversion() {
        for (let item of this.files) {
            if (item.status === 'pending') {
                await this.convertFile(item);
            }
        }
    }

    async convertFile(item) {
        item.status = 'converting';
        item.progress = 0;
        this.renderFileList();

        try {
            // 读取文件
            const arrayBuffer = await item.file.arrayBuffer();
            const uint8Array = new Uint8Array(arrayBuffer);

            // 模拟NCM解密和转码过程
            // 实际项目中这里应该使用WebAssembly模块进行解密
            const mp3Data = await this.simulateConversion(uint8Array, item);
            
            item.mp3Data = mp3Data;
            item.status = 'success';
            item.progress = 100;
        } catch (error) {
            console.error('转换失败:', error);
            item.status = 'error';
            item.progress = 0;
        }
        
        this.renderFileList();
    }

    async simulateConversion(uint8Array, item) {
        // 模拟转换进度
        const steps = 100;
        for (let i = 0; i <= steps; i++) {
            await new Promise(resolve => setTimeout(resolve, 20));
            item.progress = i;
            this.renderFileList();
        }

        // 这里应该是实际的NCM解密逻辑
        // 返回模拟的MP3数据
        return new Uint8Array(uint8Array.length * 0.8); // 模拟压缩后的MP3数据
    }

    async handleSave() {
        const successfulFiles = this.files.filter(f => f.status === 'success');
        
        if (successfulFiles.length === 0) {
            alert('没有可保存的文件');
            return;
        }

        try {
            // 检查是否支持File System Access API
            if ('showDirectoryPicker' in window) {
                const dirHandle = await window.showDirectoryPicker();
                
                for (let item of successfulFiles) {
                    const fileName = item.name.replace('.ncm', '.mp3');
                    const fileHandle = await dirHandle.getFileHandle(fileName, { create: true });
                    const writable = await fileHandle.createWritable();
                    
                    // 这里应该写入实际的MP3数据
                    // 目前使用模拟数据
                    await writable.write(item.mp3Data);
                    await writable.close();
                }
                
                alert(`成功保存 ${successfulFiles.length} 个文件`);
            } else {
                // 降级方案：逐个下载
                for (let item of successfulFiles) {
                    const blob = new Blob([item.mp3Data], { type: 'audio/mpeg' });
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = item.name.replace('.ncm', '.mp3');
                    a.click();
                    URL.revokeObjectURL(url);
                }
            }
        } catch (error) {
            console.error('保存失败:', error);
            alert('保存失败，请重试');
        }
    }

    handleClear() {
        this.files = [];
        this.renderFileList();
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    getStatusText(status) {
        const statusMap = {
            'pending': '等待转换',
            'converting': '转换中...',
            'success': '转换完成',
            'error': '转换失败'
        };
        return statusMap[status] || status;
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new NCMConverter();
});

// 实际的NCM解密函数（需要集成ncmdump-wasm）
async function decryptNCM(ncmData) {
    // TODO: 集成实际的NCM解密WebAssembly模块
    // 这里是一个占位符，实际项目中需要：
    // 1. 加载ncmdump.wasm
    // 2. 使用WebAssembly进行解密
    // 3. 返回解密后的音频数据
    
    // 示例代码：
    // const wasmModule = await WebAssembly.instantiateStreaming(fetch('ncmdump.wasm'));
    // const decrypted = wasmModule.instance.exports.decrypt(ncmData);
    // return decrypted;
    
    throw new Error('NCM解密模块未集成');
}
